package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper mapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    @Override
    public PageInfo<StrategyDetail> selectList(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<StrategyDetail> list = mapper.selectForList(qo);
        return new PageInfo<>(list);
    }


    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        StrategyContent content = strategyDetail.getStrategyContent();
        if (strategyDetail.getSequence() == null) {
            Integer max = mapper.getMaxSequence(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(max == null ? 1 : max + 1);
        }
        Date date = new Date();
        if (strategyDetail.getState() == StrategyDetail.STATE_RELEASE) {
            strategyDetail.setReleaseTime(date);
        }
        if (strategyDetail.getId() == null) {
            strategyDetail.setCreateTime(date);
            mapper.insert(strategyDetail);
            content.setId(strategyDetail.getId());
            contentMapper.insert(content);

        } else {
            mapper.updateByPrimaryKey(strategyDetail);
            content.setId(strategyDetail.getId());
            contentMapper.updateByPrimaryKey(content);
        }
    }

    @Override
    public StrategyContent getContentById(Long id) {
       return contentMapper.selectByPrimaryKey(id);
    }

    @Override
    public StrategyDetail selectById(Long id) {
        return mapper.selectByPrimaryKey(id);

    }
}
